import React, {Component} from 'react';
import {reqAllTypes, reqAllTags, reqAllBlogData, reqAddBlog, reqUpdateBlog} from "../../../api";
import {
    Card, Button, Row, Form, Col, Select,
    Input, Drawer, message
} from "antd";
import {EyeOutlined} from '@ant-design/icons';
import ReactMarkdown from "react-markdown"

const {TextArea} = Input;
const {Option} = Select;

class BlogEdit extends Component {

    state = {
        markdown: "",
        visible: false,
        types: [],
        tags: [],
        isEdit: false,
        blogId: 0,
    }

    formRef = React.createRef();

    componentDidMount() {
        this.isEdit();
        this.initAllTags();
        this.initAllTypes();
        this.highlightCallBack();
    }

    isEdit = () => {
        let {state} = this.props.location;
        console.log("state", state);
        if (state) {
            this.setState({isEdit: true, blogId: state.id});
            this.initEditForm(state.id);
        }
    }

    initEditForm = async (id) => {
        let {data} = await reqAllBlogData(id);
        this.formRef.current.setFieldsValue(data);
    }

    initAllTypes = async () => {
        let {data} = await reqAllTypes();
        this.setState({types: data});
    }

    initAllTags = async () => {
        let {data} = await reqAllTags();
        this.setState({tags: data});
    }

    componentDidUpdate() {
        this.highlightCallBack();
    }

    highlightCallBack = () => {
        document.querySelectorAll("code").forEach(block => {
            /*global hljs*/
            try {
                hljs.highlightBlock(block);
            } catch (e) {
                console.log(e);
            }
        });
    };

    look = () => {
        let element = document.getElementById("content");
        this.setState({visible: true, markdown: element.value});
    }

    onFinish = () => {
        this.formRef.current.validateFields().then(async value => {
            value.userId = localStorage.getItem("userId");
            let {status, msg} = await reqAddBlog(value);
            if (status === 0) {
                message.success(msg);
                return;
            }
            message.error(msg);
        }).catch(() => {
            message.error("必填项不能为空")
        })
    }

    updateBlog = () => {
        this.formRef.current.validateFields().then(async value => {
            value.userId = localStorage.getItem("userId");
            value.id = this.state.blogId;
            let {status, msg} = await reqUpdateBlog(value);
            if (status === 0) {
                message.success(msg);
                return;
            }
            message.error(msg);
        }).catch(() => {
            message.error("必填项不能为空")
        })
    }

    restForm = () => {
        this.formRef.current.resetFields();
    }

    render() {
        let {markdown, visible, tags, types, isEdit} = this.state;
        return (
            <Card title={
                <>
                    <Button onClick={this.look} icon={<EyeOutlined/>} danger>文章预览</Button>
                    <Button
                        style={{marginLeft: 27}}
                        onClick={() => this.props.history.replace("/admin/blogList")}>返回博客列表</Button>
                </>
            }
                  style={{height: 500}}
                  extra={<>
                      {
                          isEdit ? (<Button type="primary"
                                            onClick={this.updateBlog}>
                              发布更改
                          </Button>) : (<Button type="primary"
                                                onClick={this.onFinish}>
                              发布博文
                          </Button>)
                      }
                      <Button htmlType="button"
                              onClick={this.restForm}
                              style={{marginLeft: 17}}>
                          重置
                      </Button>
                  </>}
            >
                <Form
                    ref={this.formRef}
                    name="basic"
                >
                    <Row gutter={16}>
                        <Col span={15}>
                            <Form.Item
                                name="content"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入文章内容!',
                                    },
                                ]}
                            >
                                <TextArea style={{height: 407}} id="content"/>
                            </Form.Item>
                        </Col>
                        <Col span={9}>
                            <Form.Item
                                label="文章简介"
                                name="description"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入文章简介!',
                                    },
                                ]}
                            >
                                <TextArea rows={3}/>
                            </Form.Item>
                            <Form.Item
                                label="文章标题"
                                name="title"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入文章标题!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item
                                label="所属分类"
                                name="typeId"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择所属分类',
                                    },
                                ]}
                            >
                                <Select placeholder="请选择所属分类">
                                    {
                                        types.map(item => {
                                            return (<Option
                                                key={item.id}
                                                value={item.id}>
                                                {item.typeName}
                                            </Option>)
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="所属标签"
                                name="tagIds"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择所属标签!',
                                    },
                                ]}
                            >
                                <Select
                                    showSearch
                                    mode="multiple"
                                    allowClear
                                    placeholder="请选择所属标签"
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }
                                >
                                    {
                                        tags.map(item => {
                                            return (<Option
                                                key={item.id}
                                                value={item.id}>{item.tagName}</Option>)
                                        })
                                    }
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="版权归属"
                                name="flag"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入首图地址!',
                                    },
                                ]}
                            >
                                <Select placeholder="请选择版权归属">
                                    <Option value="原创">原创</Option>
                                    <Option value="转载">转载</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item
                                label="首图地址"
                                name="firstPicture"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入首图地址!',
                                    },
                                ]}
                            >
                                <Input/>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
                <Row className="detailed-content">
                    <Drawer
                        title="文章预览"
                        placement="left"
                        closable={false}
                        width={800}
                        onClose={() => {
                            this.setState({visible: false});
                        }}
                        visible={visible}
                    >
                        <ReactMarkdown
                            source={markdown}
                            escapeHtml={false}
                        />
                    </Drawer>
                </Row>
            </Card>
        );
    }
}

export default BlogEdit;
